<?php
/**
 * Created by PhpStorm.
 * User: DaveTang
 * Date: 2020/3/3
 * Time: 15:56
 * 用户信息缓存组件
 */

namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\Cache\Cache;
use Cake\Collection\Collection;
use Cake\ORM\Behavior\TreeBehavior;

class CategoryCacheComponent extends Component
{

    public $_cache_config = 'categories';
    private $_update_db_time = 6000;//下次更新时间（秒）
    public function initialize(array $config)
    {
        parent::initialize($config);
    }

    /**
     * 上下移动分类
     */
    public function move($id, $action='up')
    {
        $cache = $this->getVal($id);
        $controller = $this->_registry->getController();
        $controller->loadModel('Categories');
        if(empty($cache)){
            return 'category_not_found';
        }else{
            if($action == 'up'){
//                $chilldren_1 = $controller->Categories->find()
//                    ->select(['lft'])
//                    ->where(['parent_id '=>$cache['parent_id']])
//                    ->order(['lft'=>'asc'])
//                    ->first();
//                if($cache['lft'] == $chilldren_1['lft']){
//                    $this->G->error("MoveEnd");
//                    return null;
//                }
                $controller->Categories->moveUp($controller->Categories->get($id));
            }else{
//                $chilldren_1 = $controller->Categories->find()
//                    ->select(['rght'])
//                    ->where(['parent_id '=>$cache['parent_id']])
//                    ->order(['rght'=>'desc'])
//                    ->first();
//                if($cache['rght'] == $chilldren_1['rght']){
//                    $this->G->error("MoveEnd");
//                    return null;
//                }
                $controller->Categories->moveDown($controller->Categories->get($id));
            }
            if(!empty($cache['parent_id'])){
                Cache::delete('category_'.$cache['parent_id'], $this->_cache_config);
            }else{
                Cache::delete('category_'.$id, $this->_cache_config);
            }
        }
        return true;
    }

    /**
     * 新增分类
     */
    public function add($alias, $parent_id = null, $enabled = 1, $home_show, $icon, $icon_active, $gather)
    {
        if(empty($alias)){
            return 'alias_error';
        }
        $controller = $this->_registry->getController();
        $controller->loadModel('Categories');
        $category = $controller->Categories->newEntity();
        $category->parent_id = $parent_id;
        $category->alias = $alias;
        $category->enabled = $enabled;
        if(!empty($home_show)){
            $category->home_show = $home_show;
        }
        if(!empty($icon)){
            $category->icon = $icon;
        }
        if(!empty($icon_active)){
            $category->icon_active = $icon_active;
        }
        if(!empty($gather)){
            $category->gather = $gather;
        }
        $controller->Categories->save($category);
        if(!empty($parent_id)){
            Cache::delete('category_'.$parent_id);
        }
        return true;
    }

    /**
     * 删除分类
     */
    public function delete($id)
    {
        $key = 'category_'.$id;
        $controller = $this->_registry->getController();
        $controller->loadModel('Categories');
        $cache = $this->getVal($id);
        if(empty($cache)){
            return 'category_not_found';
        }else{
            $controller->Categories->deleteAll(['id'=>$id]);
            Cache::delete($key, $this->_cache_config);
            $data = $controller->Categories->find()
                ->where(['parent_id' => $id])
                ->toArray();
            if(!empty($data)){
                $controller->Categories->query()
                    ->update()
                    ->set(['parent_id'=>1])
                    ->where(['parent_id' => $id])
                    ->execute();
                foreach ($data as $k=>$v){
                    Cache::delete('category_'.$v['id'], $this->_cache_config);
                }
            }
        }
        return true;
    }

    /**
     * 获取分类
     */
    public function getVal($id)
    {
        $key = 'category_'.$id;
        $data = Cache::read($key, $this->_cache_config);
        return empty($data) ? $this->createCache($id) : $data;
    }

    /**
     * 生成分类缓存
     */
    public function createCache($id)
    {
        $key = 'category_'.$id;
        $controller = $this->_registry->getController();
        $controller->loadModel('Categories');
        $data = $controller->Categories->find()
            ->select(['id','alias','parent_id'])
            ->order(['lft asc'])
            ->toArray();
        if(empty($data)){
            return null;
        }
        $collection = new Collection($data);
        $cache = $collection->nest('id', 'parent_id')->toList();
        Cache::write($key, $cache, $this->_cache_config);
        return $cache;
    }

    /**
     * 修改分类
     */
    public function updateCache($id, $data)
    {
        $key = 'category_'.$id;
        $controller = $this->_registry->getController();
        $controller->loadModel('Categories');
        $cache = $this->getVal($id);
        if(empty($cache)){
            return 'category_not_found';
        }else{
            $controller->Categories->query()
                ->update()
                ->set($data)
                ->where(['id' => $id])
                ->execute();
            Cache::delete($key, $this->_cache_config);
        }
        return true;
    }

}